package com.ayf.payment.game.api.filter;

import com.ayf.payment.game.api.auths.AbstractAuthorization;
import com.ayf.payment.game.api.bean.AuthorizationInfo;
import com.ayf.payment.game.api.bean.WrapperHttpServletRequest;
import com.ayf.payment.game.api.dto.MerchantDTO;
import com.ayf.payment.game.api.dto.Token;
import com.ayf.payment.game.api.dto.criteria.MerchantBankCriteria;
import com.ayf.payment.game.api.entity.MerchantBank;
import com.ayf.payment.game.api.entity.MerchantSon;
import com.ayf.payment.game.api.exception.AuditedFailedException;
import com.ayf.payment.game.api.exception.AuthorizeFailedException;
import com.ayf.payment.game.api.service.MerchantBankService;
import com.ayf.payment.game.api.service.MerchantService;
import com.ayf.payment.game.api.service.MerchantSonService;
import com.ayf.payment.game.api.service.TokenRepository;
import com.ayf.payment.game.api.type.AuthorizationType;
import com.ayf.payment.game.api.type.LoginType;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.ayf.payment.game.api.utils.IPUtils;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


@WebFilter(urlPatterns = "/v/*", filterName = "authorFilter")
public class AuthorizationFilter extends BasicFilter implements Filter {

    @Autowired
    private TokenRepository tokenRepository;

    @Resource
    private AbstractAuthorization abstractAuthorization;

    @Autowired
    private MerchantService merchantService;

    @Autowired
    private MerchantSonService merchantSonService;
    @Autowired
    private MerchantBankService merchantBankService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * 处理授权
     *
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        WrapperHttpServletRequest reqWrapper = new WrapperHttpServletRequest(req);
//        LogPortal.info("{} url:[{}] ", this.getClass().getName(), req.getRequestURI());
        //需要校验的请求
        if (!isContain(req.getRequestURI(), canAlwaysVisits)) {
            try {
                //获取实例
                AbstractAuthorization authorization = abstractAuthorization.getInstanceByAuthType(req);
                //签名校验
                AuthorizationInfo authorizationInfo = authorization.execute(reqWrapper);
                reqWrapper.setPrincipal(authorizationInfo);
            } catch (Exception e) {
                handleException(res, e);
                return;
            }
        }

        AuthorizationInfo authorizationInfo = (AuthorizationInfo) reqWrapper.getUserPrincipal();
        if (authorizationInfo != null) {
            //设置Customer信息
            MerchantDTO merchantDTO = null;
            try {
                if (authorizationInfo.getAuthType() == AuthorizationType.OAUTH) {//需要校验Token
                    if (StringUtils.isBlank(authorizationInfo.getAuthValue())) {
                        throw new AuthorizeFailedException("accessToken cannot be null.URL[" + req.getRequestURI() + "]");
                    }
                    Token token;
                    String clientType = req.getHeader("clientType");
                    if(StringUtils.isNotEmpty(clientType)&& clientType.equals("gateWay")){
                         token = tokenRepository.getTokenByAccessToken(clientType+"-"+authorizationInfo.getAuthValue());
                    }else {
                         token = tokenRepository.getTokenByAccessToken(authorizationInfo.getAuthValue());
                    }
                    if (null == token) {
                        throw new AuthorizeFailedException("Authorization failed, please login again");
                    } else {
                        String ip = IPUtils.getIp(req);
                        if (!"gateWay".equals(clientType)){
                            if (!"defaultIp".equals(token.getReqIp()) && StringUtils.isNotEmpty(ip) && !ip.equals(token.getReqIp())){
                                throw new AuthorizeFailedException("Authorization failed, please login again");
                            }
                        }
                        merchantDTO = merchantService.selectMerchantDTO(token.getMerchantId());
                        if (merchantDTO == null) {
                            throw new AuthorizeFailedException("Authorization failed, please login again");
                        }
                        if (LoginType.SON.name().equals(token.getLoginType())) {
                            MerchantSon son = merchantSonService.selectInfo(token.getLoginId());
                            if (son == null) {
                                throw new AuthorizeFailedException("Authorization failed, please login again");
                            }
                        }
                        merchantDTO.setToken(authorizationInfo.getAuthValue());
                        merchantDTO.setLoginId(token.getLoginId());
                        merchantDTO.setLoginType(token.getLoginType());
                        merchantDTO.setOperIp(ip);
                        MerchantBankCriteria merchantBankCriteria = new MerchantBankCriteria();
                        merchantBankCriteria.setMerchantId(merchantDTO.getId());
                        List<MerchantBank> list = merchantBankService.selectList(merchantBankCriteria);
                        if (list == null || list.size() == 0) {
                            if (!(isContain(req.getRequestURI(), notVisits) || isContain(req.getRequestURI(),
                                    canAlwaysVisits))) {
                                throw new AuditedFailedException("The current status of the merchant is under review.");
                            }
                        }
                    }
                }
            } catch (AuthorizeFailedException | AuditedFailedException e) {
                handleException(res, e);
                return;
            }
            reqWrapper.setPrincipal(merchantDTO);
        }
        chain.doFilter(reqWrapper, res);
    }

    @Override
    public void destroy() {

    }
}
